package com.company.task2;

/*
 编程获取两个指定字符串中的最大相同子串。

 如： s1="asdafghjka", s2="aaasdfg" 他们的最大子串为"asd"
 */

import java.util.Scanner;

public class SameSubString {

    public static void main(String[] args) {

        // 输入两个字符串
        Scanner s = new Scanner(System.in);
        System.out.println("请输入第一个字符串");
        String s1 = s.next();
        System.out.println("请输入第二个字符串");
        String s2 = s.next();

        if(s1 == s2){
            System.out.println("最大子串为：" + s1);
            return;
        }

        // 找出较长的字符串
        String maxStr = s1.length() > s2.length()?s1:s2;
        String minStr = s1.length() < s2.length()?s1:s2;

        // 找公共子串
        int minStringLength = minStr.length();
        int stringLength = minStringLength;
        boolean flag = false;
        String result;
        int i;
        int j;

        while(stringLength > 0){
            for(i = 0; i+stringLength-1 < minStringLength; i++){
                j = i + stringLength;
                flag = maxStr.contains(minStr.substring(i,j));
                if(flag){
                    result = minStr.substring(i,j);
                    System.out.println("最大公共子串为：" + result);
                    return;
                }
            }
            stringLength--;
        }

        System.out.println("两个字符串无公共子串");
    }
}
